package HslCommunication;

import HslCommunication.Core.Types.OperateResult;
import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Melsec.MelsecMcNet;
import com.yhy.wxzn.wcs.device.netty.bean.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * 三菱MC驱动帮助类
 * */
@Slf4j
public class MelsecMcHelper {

    private MelsecMcNet melsecMc;
    private volatile boolean connected;

    public MelsecMcHelper(MelsecMcNet melsecMc){
        this.melsecMc = melsecMc;
    }

    public boolean connect(){
        if(!this.isConnected()){
            OperateResult connect = melsecMc.ConnectServer( );
            if(connect.IsSuccess){
                this.connected = Boolean.TRUE;
                return Boolean.TRUE;
            }else{
                this.connected = Boolean.FALSE;
                return Boolean.FALSE;
            }
        }
        return this.connected;
    }

    private boolean isConnected() {
        return this.connected;
    }

    public ResultData read(String address,int length){
        ResultData rd = null;
        if(length == 1){
            rd = this.readResultRender(this.melsecMc.ReadInt16(address));
        }else{
            rd = this.readResultRender(this.melsecMc.Read(address, (short) length));
        }
        return rd;
    }

    public ResultData write(String address, byte[] bytes){
        ResultData rd = null;
        try {
            rd = this.writeResultRender(this.melsecMc.Write(address, bytes));
        } catch (Exception var5) {
            log.error("写入byte异常{},{}", address, var5);
        }
        return rd;
    }

    private ResultData writeResultRender(OperateResult result) {
        ResultData rd = new ResultData();
        rd.setConnecd(this.isConnected());
        rd.setMessage("当前与PLC通信断开！");
        rd.setSuccess(result.IsSuccess);
        if (result.IsSuccess) {
            rd.setMessage("写入成功");
        } else {
            result.IsSuccess = false;
            this.closeConn();
            rd.setMessage(result.ToMessageShowString());
        }
        this.connected = result.IsSuccess;
        return rd;
    }

    public <T> ResultData readResultRender(OperateResultExOne<T> result) {
        ResultData rd = new ResultData();
        rd.setConnecd(this.isConnected());
        rd.setMessage("当前与PLC通信断开！");
        rd.setSuccess(result.IsSuccess);
        if (result.IsSuccess) {
            rd.setMessage("读取成功");
            rd.setValue(result.Content);
        } else {
            result.IsSuccess = false;
            this.closeConn();
            rd.setMessage(result.ToMessageShowString());
        }
        this.connected = result.IsSuccess;
        return rd;
    }

    public void closeConn() {
        if(!this.connected && !ObjectUtils.isEmpty(melsecMc)){
            melsecMc.ConnectClose();
        }
    }
}
